package com.execjar.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

@Slf4j
public class UdpUtil {

    private static int timeOut = 1000;

    /**
     * tcpPost返回指定字节的16进制字符串
     *
     * @param port 参数
     */
    public static String postRe16Self(String ip, int port, String order, int length) throws IOException {
        //传入0表示让操作系统分配一个端口号
        try (DatagramSocket socket = new DatagramSocket()) {
            socket.setSoTimeout(timeOut);
            // 指定包要发送的目的地
            byte[] sendData = toByteArray2(order);
            DatagramPacket request = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(ip), port);
            // 为接受的数据包创建空间
            DatagramPacket response = new DatagramPacket(new byte[length], length);
            socket.send(request);
            socket.receive(response);
            return byte2HexStr(response.getData());
        } catch (IOException e) {
            log.error("UDP读取异常", e);
            throw e;
        }
    }

    public static String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    public static byte[] toByteArray2(String hexString) {
        if (hexString != null && !("").equals(hexString)) {
            hexString = hexString.replace(" ", "");
            byte[] byteArray = new byte[hexString.length() / 2];
            hexString = hexString.toLowerCase();
            int k = 0;
            for (int i = 0; i < byteArray.length; i++) {//因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
                byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
                byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
                byteArray[i] = (byte) (high << 4 | low);
                k += 2;
            }
            return byteArray;
        } else {
            return null;
        }
    }
}
